package com.yohann.eduorder.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yohann.commonutils.jwt.JwtUtils;
import com.yohann.commonutils.result.R;
import com.yohann.eduorder.entity.Order;
import com.yohann.eduorder.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 订单 前端控制器
 * </p>
 *
 * @author Yohann
 * @since 2020-08-28
 */
@RestController
@RequestMapping("/order-service/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    /**
     * 添加订单
     * @param courseId
     * @return
     */
    @PostMapping("createOrder/{courseId}")
    public R saveOrder(@PathVariable String courseId, HttpServletRequest request){
        String memberId = JwtUtils.getMemberIdByJwtToken(request);

        String orderId = orderService.createOrder(courseId,memberId);

        return R.ok().data("orderId",orderId);
    }

    /**
     * 根据订单号查询订单信息
     * @param orderNo
     * @return
     */
    @GetMapping("getOrderInfo/{orderNo}")
    public R getOrderInfo(@PathVariable String orderNo){
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("order_no",orderNo);

        Order order = orderService.getOne(wrapper);

        return R.ok().data("order",order);
    }

    /**
     * 查询用户课程购买状态
     * @param courseId
     * @param memberId
     * @return
     */
    @GetMapping("isBuyCourse/{courseId}/{memberId}")
    public boolean isBuyCourse(@PathVariable String courseId, @PathVariable String memberId){
        LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Order::getCourseId,courseId);
        queryWrapper.eq(Order::getMemberId,memberId);
        queryWrapper.eq(Order::getStatus,1);

        int count = orderService.count(queryWrapper);
        if (count > 0) {
            return true;
        }

        return false;
    }
}

